import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:local_task/common/tools/collection_tools.dart';
import 'package:local_task/common/tools/date_tool.dart';
import 'package:local_task/common/tools/extensions.dart';
import 'package:local_task/controller/task_controller.dart';
import 'package:get/get.dart';
import 'package:uuid/uuid.dart';

import '../model/task_model.dart';

/// 任务列表
class TaskList extends StatelessWidget {
  TaskList({Key? key, required String title}) : super(key: key) {
    taskController.title.value = title;
  }

  final TaskController taskController = Get.put(TaskController());

  final TextEditingController taskContentEditController =
      TextEditingController();

  @override
  Widget build(BuildContext context) {
    // 根据页面类型加载不一样的数据。
    CollectionTool.removeAll(taskController.taskList);
    if (taskController.title.value == TaskType.today.desc) {
      taskController.taskList.value = taskController.listTodayData();
    } else {
      taskController.taskList.value = taskController.listAllTask();
    }

    return Scaffold(
      appBar: AppBar(
        title: ListTile(
            title: Text(taskController.title.value),
            subtitle: Text(taskController.title.value == TaskType.today.desc
                ? DateTool.parseToString(DateTime.now())
                : "")),
      ),
      body: taskListBody(),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showAddTaskView(context);
        },
        child: const Icon(Icons.add),
      ),
    );
  }

  // 展示body
  Container taskListBody() {
    return Container(
      child: Obx(() {
        return ListView(
          children: taskController.taskList.asMap().entries.map((e) {
            TaskEntity entity = TaskEntity.jsonToEntity(e.value);

            return ListTile(
                leading: Checkbox(
                  value: entity.isSuccess ?? false,
                  // value: false,
                  onChanged: (bool? value) {
                    entity.isSuccess = value!;
                    taskController.taskList[e.key] = jsonEncode(entity);
                    taskController.updateEntityStore(entity);
                  },
                ),
                title: Text(
                  entity.content,
                  style: TextStyle(
                      decoration: entity.isSuccess
                          ? TextDecoration.lineThrough
                          : TextDecoration.none),
                ),
                subtitle: Text(entity.cutOffDate == null ? "": "到期：${entity.cutOffDate}"),
                trailing: IconButton(
                  onPressed: () {
                    print("准备删除的数据：$entity");
                    taskController.deleteById(entity.id!);
                  },
                  icon: const Icon(Icons.delete),
                ));
          }).toList(),
        );
      }),
    );
  }

  /// 新增任务视图
  void showAddTaskView(BuildContext context) {
    // 弹出新增任务窗口
    showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          padding:
              EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
          child: Container(
            height: 22.0.hp,
            color: Colors.amber,
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Expanded(
                      flex: 1,
                      child: ListTile(
                        title: TextFormField(
                          decoration: const InputDecoration(
                            icon: Icon(Icons.circle),
                            hintText: '添加任务',
                          ),
                          controller: taskContentEditController,
                        ),
                        trailing: IconButton(
                            icon: const Icon(Icons.upload),
                            onPressed: () {
                              // 点击上传则进行保存。
                              taskController.saveTask(TaskEntity(
                                  id: const Uuid().v1(),
                                  content: taskContentEditController.value.text,
                                  cutOffDate: DateTool.parseToString(
                                      taskController.cutOffDate.value),
                                  remindDate: DateTool.parseToString(
                                      taskController.remindDate.value)));
                              taskContentEditController.text = "";
                              showSaveSuccessToast(context);
                            }),
                      )),
                  Expanded(
                    flex: 1,
                    child: _addTaskSetting(context),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 添加任务底部的设置选项。
  Widget _addTaskSetting(BuildContext context) {
    return ListView(
      scrollDirection: Axis.horizontal,
      children: [
        InkWell(
          onTap: () {
            showCutOffDateView(context: context, isCutOffDate: true);
          },
          child: Row(
            children: [
              const Icon(Icons.safety_check),
              Obx(() {
                return Text(taskController.cutOffDateDesc.value);
              })
            ],
          ),
        ),
        InkWell(
          onTap: () {
            showCutOffDateView(context: context, isCutOffDate: false);
          },
          child: Row(
            children: [
              const Icon(Icons.alarm),
              Obx(() {
                return Text(taskController.remindDateDesc.value);
              })

            ],
          ),
        ),
      ],
    );
  }

  /// 显示保存成功提示信息。
  void showSaveSuccessToast(BuildContext context) {
    FToast fToast = FToast().init(context);
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.greenAccent,
      ),
      child: const Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.check),
          SizedBox(
            width: 12.0,
          ),
          Text("保存成功"),
        ],
      ),
    );

    fToast.showToast(
      child: toast,
      gravity: ToastGravity.CENTER,
      toastDuration: Duration(seconds: 2),
    );
  }

  /// 显示选日期弹窗
  /// @param isCutOffDate true代表【设置截止日期】，false代表【提醒日期】
  void showCutOffDateView(
      {required BuildContext context, bool isCutOffDate = true}) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          child: Column(
            children: [
              ListTile(
                leading: const Icon(Icons.today),
                title: const Text("今天"),
                onTap: () {
                  print("=========> isCutOffDate: $isCutOffDate");

                  if (isCutOffDate) {
                    taskController.cutOffDate.value = DateTime.now();
                    taskController.cutOffDateDesc.value = "今天到期";
                  } else {
                    taskController.remindDate.value = DateTime.now();
                    taskController.remindDateDesc.value = "今天提醒";
                  }

                  Get.back();
                },
              ),
              ListTile(
                leading: const Icon(Icons.today),
                title: const Text("明天"),
                onTap: () {
                  print("=========> isCutOffDate: $isCutOffDate");
                  if (isCutOffDate) {
                    taskController.cutOffDate.value =
                        DateTime.now().add(const Duration(days: 1));
                    taskController.cutOffDateDesc.value = "明天到期";
                  } else {
                    taskController.remindDate.value =
                        DateTime.now().add(const Duration(days: 1));
                    taskController.remindDateDesc.value = "明天提醒";
                  }

                  Get.back();
                },
              ),
              ListTile(
                leading: Icon(Icons.today),
                title: Text("选择日期"),
              )
            ],
          ),
        );
      },
    );
  }
}
